<template>
  <div class="ai-floating-ball-container">
    <!-- 悬浮球 -->
    <div
      ref="floatingBall"
      class="ai-floating-ball"
      :class="{ 'dragging': isDragging, 'pulsing': aiStore.isLoading }"
      :style="ballStyle"
      @mousedown="startDrag"
      @touchstart="startDrag"
      @click="handleClick"
    >
      <!-- 球体内容 -->
      <div class="ball-content">
        <div class="ai-icon">
          <svg
            v-if="!aiStore.isLoading"
            class="w-6 h-6"
            fill="currentColor"
            viewBox="0 0 24 24"
          >
            <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />
          </svg>
          <div
            v-else
            class="loading-spinner"
          >
            <div class="spinner" />
          </div>
        </div>
        
        <!-- 状态指示器 -->
        <div
          class="status-indicator"
          :class="statusClass"
        />
      </div>
      
      <!-- 提示文字 -->
      <div
        v-if="showTooltip"
        class="ball-tooltip"
      >
        {{ tooltipText }}
      </div>
    </div>

    <!-- AI对话框 -->
    <AIDialog 
      v-if="aiStore.isDialogVisible"
      @close="aiStore.hideDialog"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useAIStore } from '@/stores/ai'
import AIDialog from './AIDialog.vue'

const aiStore = useAIStore()

// 拖拽相关状态
const floatingBall = ref(null)
const isDragging = ref(false)
const dragOffset = ref({ x: 0, y: 0 })
const showTooltip = ref(false)
const tooltipTimer = ref(null)

// 移动端交互状态
const touchStartTime = ref(0)
const touchStartPosition = ref({ x: 0, y: 0 })
const hasMoved = ref(false)
const dragThreshold = 10 // 拖拽距离阈值（像素）
const clickTimeThreshold = 300 // 点击时间阈值（毫秒）

// 计算属性
const ballStyle = computed(() => ({
  left: `${aiStore.floatingBallPosition.x}px`,
  top: `${aiStore.floatingBallPosition.y}px`,
  zIndex: aiStore.isDialogVisible ? 1001 : 1000
}))

const statusClass = computed(() => {
  if (aiStore.aiHealthStatus?.success) {
    return 'status-healthy'
  } else if (aiStore.aiHealthStatus?.success === false) {
    return 'status-error'
  }
  return 'status-unknown'
})

const tooltipText = computed(() => {
  if (aiStore.isLoading) return 'AI正在思考中...'
  if (aiStore.error) return 'AI服务异常'
  return 'AI法律助手'
})

// 拖拽功能
const startDrag = (event) => {
  const clientX = event.type === 'touchstart' ? event.touches[0].clientX : event.clientX
  const clientY = event.type === 'touchstart' ? event.touches[0].clientY : event.clientY
  
  console.log('Touch/Mouse start:', event.type, clientX, clientY)
  
  if (event.type === 'touchstart') {
    // 移动端：记录触摸开始信息，但不立即开始拖拽
    touchStartTime.value = Date.now()
    touchStartPosition.value = { x: clientX, y: clientY }
    hasMoved.value = false
    
    // 添加移动端事件监听
    document.addEventListener('touchmove', handleTouchMove, { passive: false })
    document.addEventListener('touchend', handleTouchEnd)
  } else {
    // 桌面端：立即开始拖拽
    event.preventDefault()
    isDragging.value = true
    dragOffset.value = {
      x: clientX - aiStore.floatingBallPosition.x,
      y: clientY - aiStore.floatingBallPosition.y
    }
    
    document.addEventListener('mousemove', handleDrag)
    document.addEventListener('mouseup', stopDrag)
  }
}

// 移动端触摸移动处理
const handleTouchMove = (event) => {
  const clientX = event.touches[0].clientX
  const clientY = event.touches[0].clientY
  
  // 计算移动距离
  const deltaX = Math.abs(clientX - touchStartPosition.value.x)
  const deltaY = Math.abs(clientY - touchStartPosition.value.y)
  const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
  
  console.log('Touch move distance:', distance)
  
  if (distance > dragThreshold && !isDragging.value) {
    // 超过阈值，开始拖拽
    console.log('Start dragging on mobile')
    isDragging.value = true
    hasMoved.value = true
    dragOffset.value = {
      x: touchStartPosition.value.x - aiStore.floatingBallPosition.x,
      y: touchStartPosition.value.y - aiStore.floatingBallPosition.y
    }
  }
  
  if (isDragging.value) {
    event.preventDefault()
    
    let newX = clientX - dragOffset.value.x
    let newY = clientY - dragOffset.value.y
    
    // 边界检测
    const ballSize = 60
    const maxX = window.innerWidth - ballSize
    const maxY = window.innerHeight - ballSize
    
    newX = Math.max(0, Math.min(newX, maxX))
    newY = Math.max(0, Math.min(newY, maxY))
    
    aiStore.updateFloatingBallPosition({ x: newX, y: newY })
  }
}

// 桌面端拖拽处理
const handleDrag = (event) => {
  if (!isDragging.value) return
  
  event.preventDefault()
  
  const clientX = event.clientX
  const clientY = event.clientY
  
  let newX = clientX - dragOffset.value.x
  let newY = clientY - dragOffset.value.y
  
  // 边界检测
  const ballSize = 60
  const maxX = window.innerWidth - ballSize
  const maxY = window.innerHeight - ballSize
  
  newX = Math.max(0, Math.min(newX, maxX))
  newY = Math.max(0, Math.min(newY, maxY))
  
  aiStore.updateFloatingBallPosition({ x: newX, y: newY })
}

// 移动端触摸结束处理
const handleTouchEnd = (event) => {
  console.log('Touch end, isDragging:', isDragging.value, 'hasMoved:', hasMoved.value)
  
  const touchDuration = Date.now() - touchStartTime.value
  
  // 移除事件监听
  document.removeEventListener('touchmove', handleTouchMove)
  document.removeEventListener('touchend', handleTouchEnd)
  
  if (isDragging.value) {
    // 如果是拖拽，执行拖拽结束逻辑
    stopDragMobile()
  } else if (!hasMoved.value && touchDuration < clickTimeThreshold) {
    // 如果没有移动且时间短，认为是点击
    console.log('Detected click on mobile')
    setTimeout(() => {
      handleClick(event)
    }, 50) // 短暂延迟确保状态重置
  }
  
  // 重置状态
  setTimeout(() => {
    isDragging.value = false
    hasMoved.value = false
  }, 100)
}

// 桌面端拖拽结束处理
const stopDrag = () => {
  if (!isDragging.value) return
  
  isDragging.value = false
  
  // 移除全局事件监听
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
  
  // 边缘吸附效果
  applyEdgeSnap()
}

// 移动端拖拽结束处理
const stopDragMobile = () => {
  isDragging.value = false
  
  // 边缘吸附效果
  applyEdgeSnap()
}

// 边缘吸附效果
const applyEdgeSnap = () => {
  const ballSize = 60
  const threshold = 100
  let { x, y } = aiStore.floatingBallPosition
  
  if (x < threshold) {
    x = 20 // 吸附到左边
  } else if (x > window.innerWidth - ballSize - threshold) {
    x = window.innerWidth - ballSize - 20 // 吸附到右边
  }
  
  aiStore.updateFloatingBallPosition({ x, y })
}

// 点击处理
const handleClick = (event) => {
  console.log('Handle click called, isDragging:', isDragging.value, 'hasMoved:', hasMoved.value)
  
  // 如果是拖拽结束或已经移动过，不触发点击
  if (isDragging.value || hasMoved.value) {
    console.log('Click blocked due to drag state')
    return
  }
  
  console.log('Opening AI dialog')
  event.stopPropagation()
  aiStore.showDialog()
}

// 提示文字显示
const showTooltipTemporarily = () => {
  showTooltip.value = true
  clearTimeout(tooltipTimer.value)
  tooltipTimer.value = setTimeout(() => {
    showTooltip.value = false
  }, 3000)
}

// 窗口大小变化处理
const handleResize = () => {
  const ballSize = 60
  const maxX = window.innerWidth - ballSize
  const maxY = window.innerHeight - ballSize
  
  let { x, y } = aiStore.floatingBallPosition
  
  if (x > maxX) x = maxX
  if (y > maxY) y = maxY
  
  aiStore.updateFloatingBallPosition({ x, y })
}

// 生命周期
onMounted(() => {
  // 初始化AI store
  aiStore.initialize()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
  
  // 显示初始提示
  nextTick(() => {
    showTooltipTemporarily()
  })
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  clearTimeout(tooltipTimer.value)
})
</script>

<style scoped>
.ai-floating-ball-container {
  position: fixed;
  pointer-events: none;
  z-index: 1000;
}

.ai-floating-ball {
  position: fixed;
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  cursor: pointer;
  pointer-events: auto;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: visible;
}

.ai-floating-ball:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 25px rgba(102, 126, 234, 0.6);
}

.ai-floating-ball.dragging {
  transform: scale(1.2);
  box-shadow: 0 8px 30px rgba(102, 126, 234, 0.8);
  z-index: 1002;
}

.ai-floating-ball.pulsing {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
  }
  50% {
    box-shadow: 0 6px 25px rgba(102, 126, 234, 0.8);
  }
  100% {
    box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
  }
}

.ball-content {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.ai-icon {
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  display: flex;
  align-items: center;
  justify-content: center;
}

.spinner {
  width: 24px;
  height: 24px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.status-indicator {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 2px solid white;
}

.status-healthy {
  background-color: #10b981;
}

.status-error {
  background-color: #ef4444;
}

.status-unknown {
  background-color: #f59e0b;
}

.ball-tooltip {
  position: absolute;
  bottom: -40px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  white-space: nowrap;
  pointer-events: none;
  opacity: 0;
  animation: fadeInUp 0.3s ease-out forwards;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-floating-ball {
    width: 50px;
    height: 50px;
  }
  
  .ai-icon svg {
    width: 20px;
    height: 20px;
  }
  
  .spinner {
    width: 20px;
    height: 20px;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .ball-tooltip {
    background: rgba(255, 255, 255, 0.9);
    color: #1f2937;
  }
}
</style>

